import mimetypes
import os
import smtplib
from email.message import EmailMessage


class EmailService:
    def __init__(
        self,
        email_user,
        email_app_password,
        smtp_host="smtp.gmail.com",
        smtp_port=465,
        timeout_seconds=10,
        logger=None,
    ):
        self.email_user = email_user
        self.email_app_password = email_app_password
        self.smtp_host = smtp_host
        self.smtp_port = int(smtp_port)
        self.timeout_seconds = timeout_seconds
        self.logger = logger

    def send_participant_results(
        self,
        to_email,
        participant_name,
        app_name,
        score,
        successful_cues,
        timed_out_cues,
        scoreboard_url="",
        attachment_path=None,
    ):
        message = EmailMessage()
        message["Subject"] = (
            f"{participant_name or 'Participant'} - {app_name} Results [WCB 2026]"
        )
        message["From"] = self.email_user
        message["To"] = to_email

        body_lines = [
            f"Dear {participant_name or 'Participant'},",
            "",
            f"Thanks so much for stopping by the booth today and trying out {app_name}! "
            "We hope that you not only enjoyed it, but made you think about how you can "
            "use IMUs and Haptic Feedback to help answer your novel research questions.",
            "",
            f"Average reaction time: {score:.2f} seconds",
            f"Successful cues: {successful_cues}",
            f"Timed out cues: {timed_out_cues}",
        ]
        if scoreboard_url:
            body_lines.extend(
                ["", f"You can see your rankings online {scoreboard_url}."]
            )
        body_lines.extend(
            ["", "As always, I'm happy to answer any questions you may have."]
        )

        message.set_content("\n".join(body_lines))

        if attachment_path and os.path.exists(attachment_path):
            mime_type, _ = mimetypes.guess_type(attachment_path)
            maintype, subtype = (mime_type or "application/octet-stream").split("/", 1)
            with open(attachment_path, "rb") as attachment_file:
                message.add_attachment(
                    attachment_file.read(),
                    maintype=maintype,
                    subtype=subtype,
                    filename=os.path.basename(attachment_path),
                )

        with smtplib.SMTP_SSL(
            self.smtp_host, self.smtp_port, timeout=self.timeout_seconds
        ) as smtp:
            smtp.login(self.email_user, self.email_app_password)
            smtp.send_message(message)

        if self.logger:
            self.logger.info(f"Sent Hand Flop results email to {to_email}")

if __name__ == "__main__":
    # Manual test run.
    # Set these as environment variables rather than hardcoding credentials:
    #   export EMAIL_USER="youraddress@gmail.com"
    #   export EMAIL_APP_PASSWORD="16-char app password from myaccount.google.com/apppasswords"
    #   export TEST_TO_EMAIL="recipient@example.com"

    email_user = os.environ["EMAIL_USER"]
    email_app_password = os.environ["EMAIL_APP_PASSWORD"]
    test_to_email = os.environ.get("TEST_TO_EMAIL", email_user)

    service = EmailService(
        email_user=email_user,
        email_app_password=email_app_password,
    )

    service.send_participant_results(
        to_email=test_to_email,
        participant_name="Test Participant",
        app_name="Hand Flop",
        score=0.42,
        successful_cues=8,
        timed_out_cues=2,
        scoreboard_url="https://example.com/scoreboard",
        attachment_path=None,  # e.g. "results.pdf" to test attachments
    )

    print(f"Test email sent to {test_to_email}")